#include <iostream>
#include <stdio.h>
#include "Image32.hpp"


int main(int argc, char* argv[])
{
  if (argc != 3) {
    std::cout << "Syntax: import_monsters <art_file> <palette_file>" << std::endl;
    return 1;
  }


  FILE* art_file = fopen(argv[1], "rb");
  if (art_file == NULL) {
    std::cout << "Could not open art file" << std::endl;
    return 1;
  }

  FILE* palette_file = fopen(argv[2], "rb");
  if (palette_file == NULL) {
    fclose(art_file);
    std::cout << "Could not open palette file" << std::endl;
    return 1;
  }


  CImage32 images[128];
  for (int i = 0; i < 128; i++) {
    images[i].Resize(80, 80);
  }


  // read palette
  RGB palette[256];
  fread(palette, 3, 256, palette_file);

  RGBA palette_rgba[256];
  for (int i = 0; i < 256; i++) {
    palette_rgba[i].red   = palette[i].red   * 4;
    palette_rgba[i].green = palette[i].green * 4;
    palette_rgba[i].blue  = palette[i].blue  * 4;
    palette_rgba[i].alpha = (i != 0) * 255;
  }


  for (int i = 0; i < 128; i++) {
    for (int y = 0; y < 80; y++) {
      for (int x = 0; x < 80; x++) {
        byte color = fgetc(art_file);
        images[i].GetPixels()[y * images[i].GetWidth() + x] = palette_rgba[color];
      }
    }
  }


  for (int i = 0; i < 128; i++) {
    char filename[80];
    sprintf(filename, "mpic%3d.png", i);

    std::cout << filename;
    if (images[i].Save(filename)) {
      std::cout << ": success" << std::endl;
    } else {
      std::cout << ": fail" << std::endl;
    }
  }


  fclose(art_file);
  fclose(palette_file);
  return 0;
}
